import fetch from 'isomorphic-fetch'
//import createHistory from 'history/createHashHistory'
var createHistory = require('history').createHashHistory
import msg from '../components/Message'
import loading from '../components/loading'
import urls from './urls'
const history = createHistory();
/**
 * 
 * @desc 格式化一个对象为字符串如 name=pat&city_no=020&old=99;
 * @param data string
 **/
  function parseParams(data) {
    if (data == null) {
        return '';
    }
    let list = [];
    for (let item in data) {
        list.push(`${item}=${data[item]}`)
    }
    return list.join("&");
  }
function getToken(){
  return fetch(urls.getToken,{
    credentials: 'same-origin',
  })
  .then(res=>{
    return res.json();
  })
  .then(res=>{
    localStorage.setItem('Authorization', res.data);
    return res;
  })
  .catch(e=>{
    return { code:-1,data:{},message:"请求失败，请重新操作"}
    if(actions) actions.showAlert({text:'请求失败，请重新操作',code:0})
  })
}

function form(url,data,history){
  var headers = new Headers();
  headers.append('Authorization',localStorage.getItem('Authorization'))
  headers.append('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');

    loading.show()
    const params = parseParams(data)
    return fetch(url,{
      method: 'POST',
      credentials: 'same-origin',
      headers,
      body:params
    })
    .then((res)=>{
      if(res.ok){
        return res.json();
      }else{
        return {};
      }
    })
    .then((res)=>{
      loading.hide()
      /*
      code =301,token 过期,重新请求接口
      code=300,未登录
       */
      if(res.code == 301){
        localStorage.setItem('Authorization', res.data.token);
        window.location.reload()
        //form(url,data)
        
      }else if( res.code == 300){
        history.push('/login')
      }
      if(res.code!==200 && res.code != 301){
        msg.info(res.message,0)
        
      }
      return res;
    })

}


module.exports =async (url,data,history)=>{
  
  if(!localStorage.getItem('Authorization')){
    await getToken()
    var res= await form(url,data,history)
    return res
  }else{
    var res= await form(url,data,history)
    return res
  }

  
}
